<template>
  <div class="procure-inventory">
    <header>
      <h3>按库存汇总排序</h3>
      <el-input v-model="searchkey" style="width: 280px" placeholder="请输入商品/ID/SKU编码" :prefix-icon="Search" />
    </header>

    <!-- 搜索表单 -->
    <div class="center-search-wrap">
      <div>
        <SearchForm ref="searchFormRef" :list="[...formList]" @submit="search" @reset="reset"></SearchForm>
      </div>
    </div>

    <div class="download-btn">
      <el-button type="primary" :loading="downloading" @click="downloadExcel">导出</el-button>
    </div>

    <!-- 表单数据 -->
    <el-table class="jzt-table mt20" ref="multipleTableRef" :data="list" border stripe style="width: 100%">
      <el-table-column fixed prop="date" show-overflow-tooltip label="商品信息" width="405">
        <template #default="scope">
          <div class="info">
            <div class="left">
              <img :src="scope.row.mainPicUrl" alt="" />
            </div>
            <div class="right">
              <h3 class="name" style="white-space: break-spaces; word-break: break-all">
                {{ scope.row.productAliasName || "-" }}
              </h3>
              <p style="white-space: break-spaces; word-break: break-all">
                <!-- {{ getSpes(scope.row.skuSpecification) }}     -->
                {{ scope.row.skuSpecification }}
              </p>
              <p>SKU编码：{{ scope.row.skuCode || "-" }}</p>
              <p>ID：{{ scope.row.productId || "-" }}</p>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="associateCustomer" show-overflow-tooltip label="商品分类" width="180">
        <template #default="scope">
          <span> {{ scope.row.categoryNameList?.join(">") || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="associateCode" show-overflow-tooltip label="单位" width="100">
        <template #default="scope">
          {{ getName(scope.row.productUnit) || "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="warehouseName" show-overflow-tooltip label="仓库">
        <template #default="scope">
          <!-- {{ scope.row.warehouseNameList?.join("，") }} -->
          {{
            scope.row?.warehouseInfoVOList ? scope.row.warehouseInfoVOList.map(item => item?.warehouseName || "").join(",") : "-"
          }}
        </template>
      </el-table-column>
      <el-table-column prop="lockProductNum" show-overflow-tooltip label="占用库存数量" width="180">
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="
              () => {
                currObj = scope.row;
                optionInfo2.isShow = true;
                getDetail2();
              }
            "
            >{{ scope.row.lockProductNum }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="lockProductPartNum" show-overflow-tooltip label="占用库存件量" width="180">
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="
              () => {
                currObj = scope.row;
                optionInfo2.isShow = true;
                getDetail2();
              }
            "
            >{{ scope.row.lockProductPartNum }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="curProductNum" show-overflow-tooltip label="可用库存数量" width="180" />
      <el-table-column prop="curProductPartNum" show-overflow-tooltip label="可用库存件量" width="180" />
      <el-table-column prop="newInTime" show-overflow-tooltip label="时间" width="180" />
      <el-table-column fixed="right" prop="action" label="操作" width="145">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="
              () => {
                currObj = scope.row;
                optionInfo.isShow = true;
                getDetail();
              }
            "
          >
            库存分布
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="toPath({ path: '/procure/inventory-turnover', query: { skuCode: scope.row.skuCode } })"
          >
            库存流水
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pt20 pb20" style="display: flex; justify-content: flex-end">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="pagination.sizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 库存分布弹窗 -->
    <distribution :optionInfo="optionInfo" @close="close" />
    <!-- 占用明细弹窗 -->
    <occupy :optionInfo="optionInfo2" @close="close2" />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import SearchForm from "@/components/SearchForm";
import useCodeArrStore from "@/store/modules/select";
import distribution from "./components/distribution";
import occupy from "./components/occupy";
import { ListPage } from "@/apis/procure/warehouse";
import { getcategoryList2 } from "@/apis/products/specifications";
import {
  inventorySummaryPage,
  getProductInventoryDistribution,
  getInventoryLockDetails,
  download
} from "@/apis/procure/inventory-manage";
import { useRouter } from "vue-router";
const router = useRouter();

const searchkey = ref("");
const formData = ref({});
const searchFormRef = ref();
const formList = ref([
  {
    label: "仓库",
    model: "warehouseId",
    type: "select",
    labelWidth: "70",
    data: [],
    props: { label: "warehouseName", value: "warehouseId" }
  },
  {
    label: "商品分类",
    model: "categoryIdList",
    type: "cascader",
    labelWidth: "70",
    data: [],
    props: { checkStrictly: false, expandTrigger: "hover", label: "name", value: "categoryId", multiple: true }
  }
]);
const list = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const optionInfo = ref({ isShow: false });
const optionInfo2 = ref({ isShow: false });
const currObj = ref({});

onMounted(async () => {
  const res = await ListPage({ page: 1, size: 9999 }); //仓库list
  const res2 = await getcategoryList2({ searchkey: "" }); //商品分类
  formList.value.map(item => {
    if (item.model === "warehouseId") {
      item.data = res.data.records;
    } else if (item.model === "categoryIdList") {
      item.data = res2.data;
    }
  });

  getList();
});

const toPath = obj => {
  //打开新页签
  const routeUrl = router.resolve(obj);
  window.open(routeUrl.href, "_blank");
};

//库存分布
const getDetail = () => {
  getProductInventoryDistribution({ businessSkuId: currObj.value.businessSkuId }).then(res => {
    if (res.code === 200) {
      optionInfo.value.detail = {
        ...currObj.value,
        list: res.data
      };
    }
  });
};
//占用明细
const getDetail2 = () => {
  getInventoryLockDetails({ businessSkuId: currObj.value.businessSkuId, warehouseId: formData.value.warehouseId || "" }).then(
    res => {
      if (res.code === 200) {
        optionInfo2.value.detail = {
          ...currObj.value,
          list: res.data
        };
      }
    }
  );
};

//关闭库存分布弹窗
const close = () => {
  optionInfo.value.isShow = false;
};
//关闭占用明细弹窗
const close2 = () => {
  optionInfo2.value.isShow = false;
};

// 导出
const downloading = ref(false);
const downloadExcel = async () => {
  // console.log(multipleSelection.value);
  let formData = searchFormRef.value.getFormData();
  downloading.value = true;
  const res = await download({
    warehouseId: formData.warehouseId,
    categoryIdList: formData?.categoryIdList ? formData.categoryIdList.map(item => item[item.length - 1]) : [],
    queryKey: searchkey.value
  });
  downloading.value = false;
  let url = window.URL.createObjectURL(res);
  const a = document.createElement("a");
  a.href = url;
  a.download = "库存管理.xlsx";
  a.click();
  URL.revokeObjectURL(url);
};

// const multipleTableRef = ref();
// // 多选数据
// const multipleSelection = ref([]);
// // 表格-单选-选中取消
// const handleSelection = (selection, row) => {
//   // 合并数组
//   let arr = [...multipleSelection.value, ...selection];
//   // 数据去重
//   let uniqueArr = arr.reduce((result, current) => {
//     let isDuplicate = result.some(item => item.categoryId === current.categoryId);
//     if (!isDuplicate) {
//       result.push(current);
//     }
//     return result;
//   }, []);
//   // 选中的数据是否当前变化的数组里
//   if (
//     !selection.some(item => {
//       return row.categoryId === item.categoryId;
//     })
//   ) {
//     // 没有-表明取消，在数组集合删除此数据
//     multipleSelection.value = uniqueArr.filter(item => item.categoryId !== row.categoryId);
//   } else {
//     // 有-表明选中，不做任何操作
//     multipleSelection.value = uniqueArr;
//   }
// };

// // 表格-全选-选中/取消
// const selectAllChange = selection => {
//   // 合并数组
//   let arr = [...multipleSelection.value, ...selection];
//   // 数据去重
//   let uniqueArr = arr.reduce((result, current) => {
//     let isDuplicate = result.some(item => item.categoryId === current.categoryId);
//     if (!isDuplicate) {
//       result.push(current);
//     }
//     return result;
//   }, []);
//   // 全部取消-数组集合中删除数据
//   if (selection.length == 0) {
//     list.value.forEach(row => {
//       uniqueArr = uniqueArr.filter(item => item.categoryId !== row.categoryId);
//     });
//   }
//   multipleSelection.value = uniqueArr;
// };

const getList = () => {
  inventorySummaryPage({
    queryKey: searchkey.value,
    ...formData.value,
    categoryIdList: formData.value?.categoryIdList ? formData.value.categoryIdList.map(item => item[item.length - 1]) : [],
    page: pagination.value.page,
    size: pagination.value.size
  }).then(res => {
    if (res.code === 200) {
      list.value = res.data.records;
      pagination.value.total = res.data.total;

      // // 表格多选回显
      // nextTick(() => {
      //   multipleSelection.value.forEach(row => {
      //     list.value.forEach(item => {
      //       if (row.categoryId === item.categoryId) {
      //         multipleTableRef.value.toggleRowSelection(item, true);
      //       }
      //     });
      //   });
      // });
    }
  });
};

// 表单查询组件submit回调
const search = form => {
  // console.log("查询表单数据===", form);
  if (form) {
    let _form = JSON.parse(JSON.stringify(form));
    formData.value = _form;
  } else {
    formData.value = {};
  }
  // 表格-多选数据集合清空
  // multipleSelection.value = [];
  nextTick(() => {
    getList();
  });
};
//清空查询表单
const reset = () => {
  search("");
};

//单位转换
const getName = code => {
  return useCodeArrStore().getDictName("shop_unit", code);
};

//拼接商品的sku规格
const getSpes = properties => {
  if (!properties) return "-";
  const arr = JSON.parse(properties) || [];
  if (arr.length > 1) {
    const str = arr.reduce((a, b) => {
      return a.specificationVal + "+" + b.specificationVal;
    });
    return str;
  } else if (arr.length === 1) {
    return arr[0].specificationVal;
  } else {
    return "-";
  }
};
const handleSizeChange = val => {
  pagination.value.size = val;
  getList();
};
const handleCurrentChange = val => {
  pagination.value.page = val;
  getList();
};
</script>

<style lang="scss" scoped>
.info {
  display: flex;
  .left {
    img {
      width: 80px;
      height: 80px;
      border-radius: 4px;
    }
  }
  .right {
    padding-left: 18px;
    .name {
      font-size: 14px;
      color: #3d3d3d;
      margin-bottom: 5px;
    }
    p {
      font-size: 12px;
      color: #86909c;
      margin-bottom: 5px;
    }
  }
}
.procure-inventory {
  padding: 0 20px;
  height: calc(100% - 0px);
  overflow-y: auto;
  & > header {
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e2e8f0;
    position: sticky;
    top: 0;
    z-index: 22;
    background-color: white;
    margin: 0 -20px;
    border-radius: 10px;
    h3 {
      font-size: 18px;
      font-weight: normal;
      position: relative;
      padding-left: 14px;
      &::before {
        position: absolute;
        content: "";
        width: 6px;
        height: 6px;
        border-radius: 50%;
        top: 8px;
        left: 0;
        background-color: #409eff;
      }
    }
  }
  .center-search-wrap {
    background-color: #f6f8fa;
    padding: 0 20px 0 20px;
    margin-top: 20px;
    :deep(.el-input-group__append) {
      padding: 0 !important;
    }
    & > div {
      display: flex;
      justify-content: space-between;
      padding: 20px 0 2px 0;
    }
    :deep(.el-form) {
      flex: 1;
    }
    .btn-wrap {
      width: 80px;
    }
  }
  .download-btn {
    margin-top: 20px;
  }
}
</style>
